package com.example.musicdemo.util

import com.example.musicdemo.model.LyricBean
import java.io.File
import java.nio.charset.Charset

object LyricUtil {
    fun parseLyric(file: File): List<LyricBean> {
        //创建集合
        val list = ArrayList<LyricBean>()
        //判断歌词是否为空
        if (!file.exists()) {
            list.add(LyricBean(0, "歌词加载错误"))
            return list
        }
        //读取歌词文件 返回每一行数据集合
        val linesList = file.readLines(Charset.forName("gbk"))
        for (line in linesList) {
            //解析一行
            val lineList: List<LyricBean> = parseLine(line)
            //添加到集合中
            list.addAll(lineList)
        }
        list.sortBy { it.startTime }
        return list
    }

    private fun parseLine(line: String): List<LyricBean> {
        //创建集合
        val list = ArrayList<LyricBean>()
        //解析当前行
        var arr = line.split("]")
        //获取歌词内容
        val content = arr[arr.size - 1]
        for (index in 0 until arr.size - 1) {
            if (arr[index].contains("0") ||
                arr[index].contains("1") ||
                arr[index].contains("2") ||
                arr[index].contains("3") ||
                arr[index].contains("4") ||
                arr[index].contains("5") ||
                arr[index].contains("6") ||
                arr[index].contains("7") ||
                arr[index].contains("8") ||
                arr[index].contains("9")
            ) {
                val startTime: Int = parseTime(arr[index])
                list.add(LyricBean(startTime, content))
            }
        }
        println("看看这个集合$list")
        return list
    }

    private fun parseTime(get: String): Int {
        println("我草草草$get")

        //"["这个需要去掉
        val timeS = get.substring(1)
        //切割
        val list = timeS.split(":")
        var hour = 0

        var min = 0
        var sec = 0f
        if (list.size == 3) {
            //小时
            hour = (list[0].toInt()) * 60 * 60 * 1000
            min = (list[1].toInt()) * 60 * 1000
            sec = (list[2].toFloat()) * 1000
        } else {
            min = (list[0].toInt()) * 60 * 1000
            sec = (list[1].toFloat()) * 1000
        }
        return (hour + min + sec).toInt()
    }

    fun parseLrcFromNet(lrcStr: String): List<LyricBean> {
        val list = ArrayList<LyricBean>()
        val lrcArray = lrcStr.split("\n")
        for (i in lrcArray.indices) {
            //解析一行
            val lineList: List<LyricBean> = parseLine(lrcArray[i])
            //添加到集合中
            list.addAll(lineList)
        }
        list.sortBy { it.startTime }
        return list
    }
}